package com.gcu.drivingschool.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gcu.drivingschool.common.utils.FileUtil;
import com.gcu.drivingschool.domain.dto.PageBean;
import com.gcu.drivingschool.domain.po.ExamQuestions;
import com.gcu.drivingschool.domain.vo.Result;
import com.gcu.drivingschool.service.ExamQuestionsService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qiniu.common.QiniuException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * 考试题目控制器
 *
 * @author zzr
 * @since 2024-05-16
 */
@Tag(name = "考试题目控制器", description = "考试题目控制器")
@RestController
@RequestMapping("/api/examQuestions")
@RequiredArgsConstructor
public class ExamQuestionsController {
    private final ExamQuestionsService examQuestionsService;

    /**
     * 获取考试题目
     *
     * @param pageNum
     * @param pageSize
     * @param type
     * @return
     */
    @Parameters({
            @Parameter(name = "pageNum", description = "第几页", in = ParameterIn.QUERY),
            @Parameter(name = "pageSize", description = "每页条数", in = ParameterIn.QUERY),
            @Parameter(name = "type", description = "题目类型（科目一,科目四）", in = ParameterIn.QUERY)
    })
    @Operation(summary = "获取考试题目", description = "填哪些参数代表根据这些参数查，哪些参数不填代表所有<br/>" +
            "自行组合...")
    @GetMapping
    public Result getExamQuestions(@RequestParam(required = false) Integer pageNum,
                                   @RequestParam(required = false) Integer pageSize,
                                   @RequestParam(required = false) String type) {
        //如果不传pageNum和pageSize,不分页
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = Integer.MAX_VALUE;
        }
        LambdaQueryWrapper<ExamQuestions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(type), ExamQuestions::getType, type);
        PageHelper.startPage(pageNum, pageSize);//分页
        //查询数据
        List<ExamQuestions> list = examQuestionsService.list(wrapper);
        Collections.shuffle(list);//打乱顺序
        Page p = (Page) list;
        PageBean pb = new PageBean(p.getTotal(), p.getResult());
        return Result.success(pb);
    }

    @PostMapping
    @Parameters({
            @Parameter(name = "file", description = "题目图片", in = ParameterIn.QUERY, required = true, schema = @Schema(type = "string", format = "binary")),
            @Parameter(name = "answer", description = "题目答案", in = ParameterIn.QUERY, required = true),
            @Parameter(name = "type", description = "题目类型（科目一,科目四）", in = ParameterIn.QUERY, required = true)
    })
    @Operation(summary = "添加题目", description = "添加题目")
    public Result addQuestion(@NotNull MultipartFile file,
                              @NotEmpty String answer,
                              @NotEmpty String type) throws IOException {
        String url = FileUtil.upload(file);
        ExamQuestions questions = new ExamQuestions();
        questions.setQuestion(url);
        questions.setAnswer(answer);
        questions.setType(type);
        boolean save = examQuestionsService.save(questions);
        if (!save) {
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * 删除题目
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除题目", description = "删除题目")
    @Parameter(name = "id", description = "题目id", in = ParameterIn.PATH, required = true)
    @DeleteMapping("/{id}")
    public Result delQuestion(@PathVariable("id") Integer id) {
        String question = examQuestionsService.getById(id).getQuestion();
        try {
            FileUtil.del(question);
        } catch (QiniuException e) {
            return Result.fail();
        }
        boolean remove = examQuestionsService.removeById(id);
        if (!remove) {
            return Result.fail();
        }
        return Result.success();
    }

    @Parameters({
            @Parameter(name = "id", description = "题目id", in = ParameterIn.QUERY, required = true),
            @Parameter(name = "file", description = "题目图片", in = ParameterIn.QUERY, schema = @Schema(type = "string", format = "binary")),
            @Parameter(name = "answer", description = "题目答案", in = ParameterIn.QUERY),
            @Parameter(name = "type", description = "题目类型（科目一,科目四）", in = ParameterIn.QUERY)
    })
    @Operation(summary = "修改题目",description = "修改题目")
    @PutMapping
    public Result updateQuestion(@NotNull Integer id,
                                 @RequestParam(required = false) MultipartFile file,
                                 @RequestParam(required = false) String answer,
                                 @RequestParam(required = false) String type) {
        LambdaUpdateWrapper<ExamQuestions> wrapper = new LambdaUpdateWrapper<>();
        if (file!=null){
            String question = examQuestionsService.getById(id).getQuestion();
            String url = null;
            try {
                FileUtil.del(question);
                url = FileUtil.upload(file);
            } catch (IOException e) {
                return Result.fail();
            }
            wrapper.set(StringUtils.isNotBlank(url),ExamQuestions::getQuestion,url);
        }
        wrapper.set(StringUtils.isNotBlank(answer),ExamQuestions::getAnswer,answer)
                .set(StringUtils.isNotBlank(type),ExamQuestions::getType,type)
                .eq(ExamQuestions::getId,id);
        boolean update = examQuestionsService.update(wrapper);
        if (!update){
            return Result.fail();
        }
        return Result.success();
    }
}
